package com.yuwenchao.superafflatus.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuwenchao.superafflatus.mapper.SuperTableMapper;
import com.yuwenchao.superafflatus.pojo.dto.TableDto;
import com.yuwenchao.superafflatus.pojo.entity.SuperTable;
import com.yuwenchao.superafflatus.service.impl.SuperTableServiceImpl;
import com.yuwenchao.superafflatus.utils.R;
import com.yuwenchao.superafflatus.utils.RandomUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ChaooGG
 * @since 2021-05-31
 */
//@CacheConfig(cacheNames = "superTable",cacheManager = "cacheManager")
@RestController
@RequestMapping("/superTable")
@Api(tags = "数据表格测试")
@Slf4j
public class SuperTableController {

    @Autowired
    SuperTableServiceImpl superTableService;
    @Autowired
    SuperTableMapper superTableMapper;

  /*  @Autowired
    CacheManager cacheManager;
*/

    @Autowired
    RedisTemplate redisTemplate;


    @ApiOperation("查询数据表格信息列表")
    @GetMapping("getTablePage")
    public R getTablePage(@RequestParam(value="page",defaultValue="1") Integer page,
                            @RequestParam(value="limit",defaultValue="10") Integer limit){
        Page<SuperTable> pageParam = new Page<>(page,limit);
        Page<SuperTable> infoPage = superTableService.page(pageParam,null);
        //Cache cache = cacheManager.getCache("cache");
       // cache.put("infoPageCache",infoPage);

        return R.ok().data("infoPage",infoPage);
    }

    @ApiOperation("随机生成10条数据")
    @PostMapping("batchsavesuperTable")
    public R batchsavesuperTable(){

        superTableService.batchsavesuperTable();
       return R.ok().message("批量插入10条数据成功！");
    }

//layuiTable相关接口
    @ApiOperation("数据表格列表")
    @GetMapping("getLayuiSearch")
    public Map getLayuiSearch(@RequestParam(value="page",defaultValue="1") Integer page,
                                        @RequestParam(value="limit",defaultValue="10") Integer limit){

     //   Map tableMap = redisTemplate.opsForHash().entries("tableMap");

      //  if (tableMap.size()==0){
            Page<SuperTable> pageParam = new Page<>(page,limit);


            Page<SuperTable> infoPage = superTableService.page(pageParam,null);
            Map<String,Object> map = new HashMap<>();
            map.put("count", infoPage.getTotal());
            map.put("data", infoPage.getRecords());
            map.put("code", 0);
            map.put("msg", "");


         //   redisTemplate.opsForHash().putAll("tableMap",map);
         //   log.info("向redis中存入数据!");

            return map;
       // }

       // log.info("从redis中获取到数据!");
     //   return tableMap;
    }

    @ApiOperation("数据表格搜索查询")
    @PostMapping("/queryUserByOther")
    public Map queryUserByOther(@RequestParam(value="page",defaultValue="1") Integer page,
                                @RequestParam(value="limit",defaultValue="10") Integer limit,
                                @RequestParam(value="superName",required = false) String superName,
                                @RequestParam(value="superMobile",required = false) String superMobile,
                                @RequestParam(value="superEmail",required = false) String superEmail,
                                @RequestParam(value="superAddress",required = false) String superAddress,
                                HttpSession session){
        //session.invalidate();
        Page<SuperTable> pageParam = new Page<>(page,limit);
        QueryWrapper<SuperTable> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.like(StringUtils.isNotBlank(superName),"super_name",superName)
                .eq(StringUtils.isNotBlank(superMobile),"super_mobile",superMobile)
                .eq(StringUtils.isNotBlank(superEmail),"super_email",superEmail)
                .like(StringUtils.isNotBlank(superAddress),"super_address",superAddress);
        //session.setAttribute("infoQueryWrapper", infoQueryWrapper);
        if(StringUtils.isNotBlank(superName)){
            session.setAttribute("name",superName);
        }
        if(StringUtils.isNotBlank(superMobile)){
            session.setAttribute("iphone",superMobile);
        } if(StringUtils.isNotBlank(superEmail)){
            session.setAttribute("email",superEmail);
        } if(StringUtils.isNotBlank(superAddress)){
            session.setAttribute("address",superAddress);
        }

        Page<SuperTable> infoPage = superTableService.page(pageParam,infoQueryWrapper);
        //        //返回值对象信息
        HashMap<String,Object> map = new HashMap<>();
        map.put("count", infoPage.getTotal());
        map.put("data", infoPage.getRecords());
        map.put("code", 0);
        map.put("msg", "");
        //
        return map;
    }


    /**
     * 单个删除
     */
    @ApiOperation("根据id删除")
    @DeleteMapping("delInfo/{id}")
    public R delInfo(@PathVariable Integer id) {
        superTableMapper.deleteById(id);
        return R.ok();
    }


    @ApiOperation("批量删除")
    @DeleteMapping("delInfoAll")
    public R delInfoAll(@RequestParam("ids") String ids) {
        //System.out.println("获取到的ids"+ids);
        if(ids.contains(",")) {
            List<Integer> list = new ArrayList<>();
            String[] split =ids.trim().split(",");
            for (String string : split) {
                list.add(Integer.parseInt(string));
            }
            System.out.println(list);
            superTableMapper.deleteBatchIds(list);
        }else {
            Integer id = Integer.parseInt(ids);
            superTableMapper.deleteById(id);
        }
        return R.ok();
    }

    @ApiOperation("新增员工")
    @PostMapping("saveInfo")
    public R saveEmp(@RequestBody SuperTable superTable){
        int insert = superTableMapper.insert(superTable);
        if(insert>0){
            return R.ok().message("添加成功！");
        }
        return R.error().message("添加失败！");

    }


    @ApiOperation("根据id修改")
    @PostMapping("editInfoById/{id}")
    public R editInfoById(@PathVariable Integer id,@RequestBody SuperTable superTable) {

        superTableMapper.updateById(superTable);
        return R.ok();
    }



    //用session获取查询条件
    @ApiOperation("Excel批量数据导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response, HttpServletRequest request, HttpSession session){

        try {
            // 这里注意使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String sixBitRandom = RandomUtils.getSixBitRandom();//随机生成6位数
            String name = (String) session.getAttribute("name");
            String iphone = (String) session.getAttribute("iphone");
            String email = (String) session.getAttribute("email");
            String address = (String) session.getAttribute("address");
            System.out.println("获取到的name"+name);
            System.out.println("获取到的iphone"+iphone);
            System.out.println("获取到的email"+email);
            System.out.println("获取到的address"+address);

            QueryWrapper<SuperTable> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(StringUtils.isNotBlank(name),"super_name",name)
                    .eq(StringUtils.isNotBlank(iphone),"super_mobile",iphone)
                    .eq(StringUtils.isNotBlank(email),"super_email",email)
                    .like(StringUtils.isNotBlank(address),"super_address",address);

            String fileName = URLEncoder.encode("员工列表_"+sixBitRandom, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TableDto.class).sheet("员工信息").doWrite(superTableService.listInfoData(queryWrapper));
            //session.invalidate(); //session失效
            Enumeration em = request.getSession().getAttributeNames();  //得到session中所有的属性名
            while (em.hasMoreElements())
                request.getSession().removeAttribute(em.nextElement().toString()); //遍历删除session中的值
        } catch (IOException e) {
            //EXPORT_DATA_ERROR(104, "数据导出失败"),
            //  throw  new BusinessException(ResponseEnum.EXPORT_DATA_ERROR, e);
            log.info("数据导出失败");
        }
    }



    @ApiOperation("Excel批量数据导入")
    @PostMapping("/importInfo")
    public R batchImport(
            @ApiParam(value = "Excel文件", required = true)
            @RequestParam("file") MultipartFile file) {
        String msg;
        String error;
        try {
            InputStream inputStream = file.getInputStream();
            superTableService.importData(inputStream);
            msg="批量导入数据成功";
            return R.ok().message(msg);
        } catch (Exception e) {
            //UPLOAD_ERROR(-103, "文件上传错误"),
            //throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
            msg ="文件上传错误!";
            error ="请检查上传文件数据及格式是否正确。";
            log.info(msg);
        }
        return R.ok().data("error",error).message(msg+" "+error);
    }
}

